package com.itheima.LockTest;

import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @PackageName: com.itheima.LockTest
 * @ClassName: ReadWriteLock
 * @Author: Renyz
 * @Date: 2021/11/12 12:05
 * @Description: //TODO
 */
//实现读写锁
@Component
public class ReadWriteLock {
    //及时把缓存刷回内存，可以让读读到最新的数据
    static volatile HashMap<String, Object> hashmap = new HashMap<String,Object>();
    //juc提供的读写锁， 读写锁都在这个类中
    static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    //写锁
    public static void getWrite(String key , String value){
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        try{
            writeLock.lock();
            Thread.sleep(30);
            System.out.println(Thread.currentThread().getName()+"获得写锁");
            hashmap.put(key, value);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();
        }
    }
    //读锁
    public static void getRead(){
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        try{
            readLock.lock();
            System.out.println(Thread.currentThread().getName()+"获得读锁");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();
        }
    }



}
